#include "tiles.h"
#include <string>
#include <iostream>

using namespace std;

Tiles::Tiles()
{
	//cerr << "entra al constructor por defecto de tile" << endl;
	m_image= NULL;
	m_file= "tiles/free.bmp";
	m_type= "free";
}

Tiles::Tiles(const string file, const string type)
{
	//cerr << "entra al constructor parametrico de tile" << endl;
	m_file= file;
	m_type= type;
	cargarImagen(m_file);

}

Tiles::Tiles( const Tiles& otra)
{
	//cerr << "entra al constr por copia de Tiles" << endl;
	copiar( otra );
}

Tiles::~Tiles()
{
	//cerr << "destructor de tile" << endl;
	borrar();
}

Tiles& Tiles::operator=(const Tiles& otra)
{
	//cerr << "entra al operator= de Tiles" << endl;
	if( this != &otra)
	{
		borrar();
		copiar( otra );
	}
	return *this;
}

bool Tiles::operator==(const Tiles& otra) const
{
	return m_file == otra.m_file && m_type == otra.m_type; //no estoy comparando las imagenes
}

void Tiles::borrar()
{
	m_file= "";
	m_type= "";

	SDL_FreeSurface(m_image); // es seguro pasar m_image == null, la la funcion no hace nada
}

void Tiles::copiar( const Tiles& otra )
{
	//cerr << "entra a copiar de tile" << endl;
	m_type= otra.m_type;
	m_file= otra.m_file;

	//cerr << "m_type: " << m_type << " m_file: " << m_file << endl;

	if(otra.m_image != NULL)
	{
		cargarImagen(m_file);
	}
	else
	{
		m_image= NULL;
	}
}

void Tiles::cargarImagen( string file)
{
	//cerr << "cargarImagen de tile" << endl;
	SDL_Surface* temp= SDL_LoadBMP( file.c_str() );
	if(temp == NULL ) // Check for validity.
	{
		cerr << "Unable to load tile: \n" << SDL_GetError() << endl;
	}
	m_image= SDL_DisplayFormat(temp);
	SDL_FreeSurface(temp);
}

void Tiles::render(SDL_Surface* surf, SDL_Rect* r_dest, const int& x, const int& y)
{
	//cerr << "render de tile" << endl;
	if(m_image != 0)
	{
		SDL_Rect* rect= new SDL_Rect;
		rect->x= 0;
		rect->y= 0;
		rect->w= m_image->w;
		rect->h= m_image->h;

		r_dest->w=m_image->w;
		r_dest->h=m_image->h;
		if( SDL_BlitSurface( m_image, rect, surf, r_dest) == -1)
		{
			cerr << "Unable to Render Tile \n" << SDL_GetError() << endl;
		}

		delete rect;
	}
}

const string Tiles::type() const
{
	return m_type;
}

const string Tiles::file() const
{
	return m_file;
}
